<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>练习4</title>
</head>

<body>

</body>
<script>
    //1.求斐波那契数列Fibonacci中的第n个数是多少？      1 1 2 3 5 8 13 21...
    function fib(n) {
        if (n == 1 || n == 2) return 1;
        return fib(n - 1) + fib(n - 2);
    }
    console.log(`第10个数为${fib(10)}`);


    //2.输入一个年份，判断是否是闰年[闰年：能被4整数并且不能被100整数，或者能被400整数]
    function isLeapYear(year) {
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            return "闰年";
        } else {
            return "平年";
        }
    }

    console.log("2000年是闰年还是平年: " + isLeapYear(2000));
    console.log("1900年是闰年还是平年: " + isLeapYear(1900));


    //3.和电脑猜拳10次(电脑出拳用随机数)，显示每次结果，最后累计输赢平局结果
    function game() {
        let playerWins = 0;
        let computerWins = 0;
        let equal = 0;

        let choices = ['石头', '剪刀', '布'];

        console.log("猜拳游戏开始！共进行10次对决");

        for (let round = 1; round <= 10; round++) {
            let playerInput;
            while (true) {
                playerInput = prompt(`第${round}轮 , 请输入你的选择（石头/剪刀/布）：`);

                if (playerInput === null) {
                    alert("游戏已取消")
                    return;
                }

                playerInput = playerInput.trim();

                if (choices.includes(playerInput)) {
                    break;
                } else {
                    alert("输入无效！请输入'石头'、'剪刀'或'布'");
                }
            }

            let playerIndex = choices.indexOf(playerInput);
            let computerIndex = Math.floor(Math.random() * 3);

            let result;
            if (playerIndex == computerIndex) {
                result = "平局";
                equal++;
            } else if (
                (playerIndex === 0 && computerIndex === 1) ||
                (playerIndex === 1 && computerIndex === 2) ||
                (playerIndex === 2 && computerIndex === 0)
            ) {
                result = "你赢了";
                playerWins++;
            } else {
                result = "电脑赢了";
                computerWins++;
            }

            console.log(`第${round}轮：你出了${choices[playerIndex]}，电脑出了${choices[computerIndex]} : ${result}`);
        }

        console.log("游戏结束！最终结果：");
        console.log(`你赢了 ${playerWins} 次`);
        console.log(`电脑赢了 ${computerWins} 次`);
        console.log(`平局 ${equal} 次`);

        if (playerWins > computerWins) {
            console.log("恭喜！你赢得了比赛！");
        } else if (computerWins > playerWins) {
            console.log("很遗憾，电脑赢得了比赛。");
        } else {
            console.log("比赛结果是平局！");
        }

        alert(`游戏结束！\n你赢了 ${playerWins} 次\n电脑赢了 ${computerWins} 次\n平局 ${equal} 次\n${playerWins > computerWins ? "恭喜！你赢得了比赛！" :
            computerWins > playerWins ? "很遗憾，电脑赢得了比赛。" :
                "比赛结果是平局！"
            }`);
    }

    game();

</script>

</html>